<template>
  <!-- 小说列表 -->
  <el-form :inline="true" class="demo-form-inline">
    <el-form-item label="小说名称:">
      <el-input v-model="productPage.query" placeholder="请输入小说名称" clearable />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="fetchNovels">查询</el-button>
      <el-button type="danger" @click="onDelete">批量删除</el-button>
    </el-form-item>
  </el-form>

  <!-- 数据表格 -->
  <el-table :data="productData" style="width: 100%">
    <el-table-column fixed prop="id" label="编号" width="60" />
    <el-table-column prop="name" label="小说名称" width="180" />
    <el-table-column prop="cover_img" label="封面" width="90">
      <template #default="scope">
        <img :src="scope.row.cover_img" alt="封面" width="60" height="80">
      </template>
    </el-table-column>
    <el-table-column prop="publisher" label="出版社" width="150" />
    <el-table-column prop="publish_date" label="发行日期" width="120" />
    <el-table-column label="更新时间" width="160">  <!-- 修改为自定义标签 -->
      <template #default="scope">
        {{ formatUpdateTime(scope.row.update_time) }}
      </template>
    </el-table-column>
    <el-table-column prop="status" label="状态" width="90">
      <template #default="scope">
        <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
          {{ scope.row.status === 0 ? '正常' : '下架' }}
        </el-tag>
      </template>
    </el-table-column>

    <el-table-column fixed="right" label="操作" width="180">
      <template #default="scope">
        <el-button size="small" @click="handleStatus(scope.row)">
          {{ scope.row.status === 0 ? '下架' : '上架' }}
        </el-button>
        <el-button type="primary" size="small" @click="editItem(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 在表格下方添加分页组件 -->
  <el-pagination
    v-model:current-page="productPage.pageNum"
    v-model:page-size="productPage.pageSize"
    :page-sizes="[10, 20, 50, 100]"
    :total="total"
    layout="total, sizes, prev, pager, next, jumper"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin: 20px"
  />

</template>

<script setup>

// 新增分页相关响应式数据
const total = ref(0)



import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'  // 补充Element Plus消息导入

const productData = ref([])
const productPage = ref({
  query: '',
  pageNum: 1,
  pageSize: 10
})

// 日期格式化函数（关键修改）
const formatUpdateTime = (timeStr) => {
  if (!timeStr) return '未设置'  // 处理空值
  try {
    const date = new Date(timeStr)
    if (isNaN(date.getTime())) {  // 检查是否为有效日期
      return `无效格式: ${timeStr}`  // 保留原始值便于调试
    }
    // 格式化为中文友好格式（YYYY-MM-DD HH:mm:ss）
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return `解析失败: ${timeStr}`  // 捕获异常并提示
  }
}

// 获取小说数据（关键修改）
const fetchNovels = async () => {
  try {
    const response = await axios.get('http://localhost:8000/user/novels/', {
      params: {
        search: productPage.value.query,
        page: productPage.value.pageNum,
        page_size: productPage.value.pageSize
      }
    })
     productData.value = response.data.data
    total.value = response.data.total


    // 数据映射时保持原始时间格式，由格式化函数处理
    productData.value = response.data.data.map(item => ({
      ...item,
      publish_date: item.publish_date ? new Date(item.publish_date).toLocaleDateString() : '未设置',
      // update_time 不提前转换，由模板中的formatUpdateTime处理
    }))

  } catch (error) {
    console.error('数据加载失败:', error)
    ElMessage.error('数据加载失败，请检查网络连接')
  }
}

// 修改状态（保持不变）
const handleStatus = async (row) => {
  try {
    const newStatus = row.status === 0 ? 1 : 0
    await axios.patch(`http://localhost:8000/user/novels/${row.id}/`, {
      status: newStatus
    })
    row.status = newStatus
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

// 初始化加载（保持不变）
onMounted(() => {
  fetchNovels()
})

// 其他方法（保持不变）
const onDelete = () => {}
const editItem = () => {}

// 新增分页事件处理
const handleSizeChange = (newSize) => {
  productPage.value.pageSize = newSize
  productPage.value.pageNum = 1
  fetchNovels()
}

const handleCurrentChange = (newPage) => {
  productPage.value.pageNum = newPage
  fetchNovels()
}

</script>

<style scoped>
.el-form {
  margin: 20px;
}

.el-table {
  margin: 0 20px;
}

img {
  object-fit: cover;
  border-radius: 4px;
}
</style>